package com.dljd.demo;

import com.dljd.constant.MqConstant;
import com.dljd.domain.MsgModel;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.Test;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author limin
 * @date 2025-06-16 00:17
 * @description
 */
public class FOrderlyTest {
    private List<MsgModel> msgModels = Arrays.asList(
            new MsgModel("qwer",1,"下单"),
            new MsgModel("qwer",1,"短信"),
            new MsgModel("qwer",1,"物流"),

            new MsgModel("zxcv",2,"下单"),
            new MsgModel("zxcv",2,"短信"),
            new MsgModel("zxcv",2,"物流")
    );
    @Test
    public void orderlyProudcer() throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("order-produce-group");
        producer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        producer.start();
        //这样消费者拿到的是乱的，要顺序打包然后在发送
//        for(int i = 0; i < 10; i++){
//            Message message = new Message("orderlyTopic",("我是第" + i + "消息").getBytes());
//            producer.send(message);
//        }

        //发送顺序消息，发送时要确保有序，并且（同一个用户的消息）要发送到同一个队列里面
        msgModels.forEach(msgModel -> {
            Message message = new Message("orderlyTopic", msgModel.toString().getBytes());
            try {
                //发 相同的订单号的去相同的队列
                producer.send(message,new MessageQueueSelector(){
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                       //在这里 选择队列 (让其分布均匀)
                        int hashCode = arg.toString().hashCode();
                        //  %
                        int i = hashCode%mqs.size();
                        return mqs.get(i);
                    }
                },msgModel.getOrderSn());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        producer.shutdown();
        System.out.println("发送完成");
    }

    @Test
    public void orderlyConsumer() throws Exception{
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("orderly-consumer-group");
        consumer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        consumer.subscribe("orderlyTopic", "*");
        // MessageListenerConcurrently  并发模式  多线程的  重试16次还失败，放入死信队列
//        consumer.registerMessageListener(new MessageListenerConcurrently(){
//            @Override
//            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
//                System.out.println(new String(msgs.get(0).getBody()));
//                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//            }
//        });


        //MessageListenerOrderly  顺序模式  单线程（每个组对应一个线程） 无线重试Integer.Max_Value
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                System.out.println("线程id" + Thread.currentThread().getId());
                System.out.println(new String(msgs.get(0).getBody()));
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();
        System.out.println("我先执行");
        System.in.read();
    }
}
